import * as Cesium from 'cesium'
import { onUnmounted } from 'vue'
import type { BillboardManager } from '../utils'
// import type { BillboardController } from '../utils'

export function useBillboardHover(billboardManager: BillboardManager) {
  const viewer = billboardManager.viewer
  const handler = viewer.screenSpaceEventHandler
  let tooltip: HTMLDivElement | null = null
  let hoveredBillboard: Cesium.Billboard | null = null

  handler.setInputAction((movement: Cesium.ScreenSpaceEventHandler.MotionEvent) => {
    const pickedObject = viewer.scene.pick(movement.endPosition)
    if (pickedObject && pickedObject.primitive instanceof Cesium.Billboard) {
      if (hoveredBillboard && hoveredBillboard !== pickedObject.primitive) {
        hoveredBillboard.scale = 1
        viewer.canvas.style.cursor = ''
        if (tooltip) tooltip.style.display = 'none'
      }

      pickedObject.primitive.scale = 1.2
      viewer.canvas.style.cursor = 'pointer'
      hoveredBillboard = pickedObject.primitive

      const position = pickedObject.primitive.position
      const canvasPosition = viewer.scene.cartesianToCanvasCoordinates(position)

      const label = billboardManager.findBillboard(pickedObject.primitive)?.label || ''

      if (canvasPosition && label) {
        // 延迟创建tooltip
        if (!tooltip) {
          tooltip = document.createElement('div')
          tooltip.style.position = 'absolute'
          tooltip.style.backgroundColor = 'rgba(0,0,0,0.7)'
          tooltip.style.color = 'white'
          tooltip.style.padding = '5px 10px'
          tooltip.style.borderRadius = '3px'
          tooltip.style.pointerEvents = 'none'
          tooltip.style.display = 'none'
          tooltip.style.transform = 'translate(-50%, -100%)'
          tooltip.style.whiteSpace = 'nowrap'
          tooltip.style.lineHeight = 'normal'
          document.body.appendChild(tooltip)
        }

        const tooltipOffset = 40
        const tooltipTop = canvasPosition.y - tooltipOffset

        tooltip.style.display = 'block'
        tooltip.style.left = `${canvasPosition.x}px`
        tooltip.style.top = `${tooltipTop}px`
        tooltip.textContent = label
      }
    } else if (hoveredBillboard) {
      hoveredBillboard.scale = 1
      viewer.canvas.style.cursor = ''
      hoveredBillboard = null
      if (tooltip) tooltip.style.display = 'none'
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

  const removeBillboardHover = () => {
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    if (tooltip) {
      document.body.removeChild(tooltip)
    }
  }

  onUnmounted(() => {
    removeBillboardHover()
  })

  return {
    removeBillboardHover,
  }
}
